//
//  ParserRSS.m
//  Demo
//
//  Created by LAZYGUY on 25/08/2011.
//  Copyright 2011 HUTECH. All rights reserved.
//

#import "ParserRSS.h"
#import "News.h"

@implementation ParserRSS
@synthesize currentLink,currentTitle,currentElement,currentSummary,currentDate,currentImgLink;
@synthesize news,newsArray,responseData;

//connecting URL
- (void)parseRssFeed:(NSString *)url withDelegate:(id)aDelegate {  
    [self setDelegate:aDelegate];  
    
    responseData = [[NSMutableData data] retain];  
    NSURL *baseURL = [[NSURL URLWithString:url] retain];  
    
    
    NSURLRequest *request = [NSURLRequest requestWithURL:baseURL];  
    
    [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];  
}  
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response  
{  
    [responseData setLength:0];  
}  

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data  
{  
    [responseData appendData:data];  
}  

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error  
{  
    NSString * errorString = [NSString stringWithFormat:@"Unable to download xml data (Error code %i )", [error code]];  
    NSLog(@"%@",errorString);
    UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Error loading content" message:errorString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];  
    [errorAlert show];  
}  

- (void)connectionDidFinishLoading:(NSURLConnection *)connection  
{  
    self.newsArray = [[NSMutableArray alloc] init];  
    
    NSXMLParser *parserRSS = [[NSXMLParser alloc] initWithData:responseData];  
    
    [parserRSS setDelegate:self];  
    [parserRSS parse];  
//    [parserRSS release];
}  

//parsing XML
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{  
    
    currentElement = [elementName copy];  
//    NSLog(@"Current Element: %@",currentElement);
    if ([elementName isEqualToString:@"item"]) {  
        news = [[News alloc]init]; 
        self.currentTitle = [[NSMutableString alloc] init];  
        self.currentSummary = [[NSMutableString alloc] init];  
        self.currentLink = [[NSMutableString alloc] init];  
        self.currentImgLink = [[NSMutableString alloc] init];
        self.currentDate = [[NSMutableString alloc] init];
    }  
    
}  

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{  
    
    if ([elementName isEqualToString:@"item"]) {  
        [news setTitleNews:currentTitle];
        [news setPubDate:currentDate];
        [news setLinkNews:currentLink];
        [news setSummaryNews:[self parseDescriptionGetSummary2:currentSummary]];
        NSString *tempString = [self parseDescriptionGetImageLink2:currentSummary];
        [news setImgLinkNews:tempString];
        if (tempString!=nil) {
        NSData *imgData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:tempString]];
        UIImage *tempImg = [[UIImage alloc] initWithData:imgData];
        [news setImageNews:tempImg];
            [imgData release];
            
            [tempImg release];
        }else{
            [news setImageNews:[UIImage imageNamed:@"noImage.gif"]];
        }
        
        [newsArray addObject:news];
        
       [tempString release];
    }  
}  

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{  
//    NSLog(@"found Character: %@", string);
    if ([currentElement isEqualToString:@"title"]) {  
        [self.currentTitle appendString:string];  
    } else if ([currentElement isEqualToString:@"link"]) {  
        [self.currentLink appendString:string];
    } else if ([currentElement isEqualToString:@"pubDate"]) {  
        [self.currentDate appendString:string];
    } else if ([currentElement isEqualToString:@"description"]) {  
        [self.currentSummary appendString:string];  
    }
}
//parser VNEpress - ko dc chuan? lam
- (NSMutableString*)parseDescriptionGetSummary:(NSMutableString *)description
{
    
    NSString *tempSummary = [[NSString alloc]init];
    NSArray *tempArray = [description componentsSeparatedByString:@">"];
    int i=0;
    i  = [tempArray count];
//    NSLog(@"number of item in Array:  %i",i);
    if (i>1) {
        
        tempSummary = [tempArray objectAtIndex:3];
        
        return (NSMutableString*)tempSummary;
    } else if(i==1)
    {        
        return description;
    }
    
    
    [tempSummary release];
    
}

- (NSMutableString*)parseDescriptionGetImageLink:(NSMutableString *)description
{
    
    
    NSString *tempImageLink = [[NSString alloc]init];
    NSArray *tempArray = [description componentsSeparatedByString:@">"];
    int i  = [tempArray count];
    
    if (i>1) {
        
        tempImageLink = (NSMutableString*)[tempArray objectAtIndex:1];        
        tempImageLink = [tempImageLink stringByReplacingOccurrencesOfString:@"<img src=" withString:@""];
        tempImageLink = [tempImageLink stringByReplacingOccurrencesOfString:@"\"" withString:@""];
//        NSLog(@"%@",tempImageLink);
        return  (NSMutableString*)tempImageLink;
    } else if(i==1)
    {        
        return nil;
    }
    
    
    [tempImageLink release];
//    [tempArray release];
}

//Parser new --- cai nay chuan? hon hjhj - dung cho ca? tuoi tre va vnexpress
- (NSMutableString*)parseDescriptionGetSummary2:(NSMutableString *)description{
    NSMutableString *string;
    NSScanner *scanString =[NSScanner scannerWithString:description];
    while ([scanString isAtEnd]==NO) {
        [scanString scanUpToString:@"<" intoString:NULL];
        [scanString scanUpToString:@">" intoString:&string];
        
    description = [description stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",string] withString:@""];
    }
    NSLog(@"%@",description);
//    return [description stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //dung cho tuoi tre
    return description; // dung cho vnexpress
}
- (NSMutableString*)parseDescriptionGetImageLink2:(NSMutableString *)description
{
    NSArray *tempArray = [description componentsSeparatedByString:@"src"];
    if ([tempArray count]>1) {
        
    
    NSMutableString *tempString = [tempArray objectAtIndex:1];
    NSArray *tempArray2 = [tempString componentsSeparatedByString:@"\""];
    NSMutableString *tempString2 = [tempArray2 objectAtIndex:1];
    NSLog(@"Link: %@",tempString2);
    return tempString2;
    }else{
        return nil;
    }
}
- (id)delegate
{
    return _delegate;
}

- (void)setDelegate:(id)new_delegate {
	_delegate = new_delegate;
}

- (void)parserDidEndDocument:(NSXMLParser *)parser {  
    if ([_delegate respondsToSelector:@selector(receivedItems:)]) { 
        [_delegate receivedItems:newsArray]; 
        NSLog(@"Number of News: %i",[newsArray count]);
        [newsArray removeAllObjects];
        [newsArray release];
    }else {   
        [NSException raise:NSInternalInconsistencyException  
                    format:@"Delegate doesn't respond to receivedItems:"];  
    }  
    
}



- (void)dealloc
{
    [responseData release];
    [newsArray release];
    [news release];
//    [currentDate release];
//    [currentElement release];
//    [currentImgLink release];
//    [currentLink release];
//    [currentTitle release];
//    [currentSummary release];
    [super dealloc];
}
@end
